<template>
  <div class="home">
    <div class="add">
      <el-button type="primary" @click="handleAdd">增加</el-button>
    </div>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="date" label="Date" width="180" />
      <el-table-column prop="name" label="Name" width="180" />
      <el-table-column prop="address" label="Address" />
      <el-table-column fixed="right" label="Operations" width="120">
        <template #default="scope" >
          <el-button link type="primary" size="small" @click="handleEdit(scope.row,scope.$index)"
            >编辑</el-button
          >
          <el-button link type="primary" size="small" @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="title" width="60%">
      <el-form :model="form" label-width="80px" class="demo-form-inline">
        <el-form-item label="日期" prop="date">
          <el-input v-model="form.date"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false?true:false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit()"> 确 定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import axios from 'axios'
import { ref, reactive } from 'vue'
const tableData = ref([])
const dialogVisible = ref(false)

//判断添加还是修改
let isAdding = ref(false);
// 用于保存正在编辑的行的 ID
let editingId = ref(null);
let form = reactive({
  date: '',
  name: '',
  address: '',
})
const title = ref('添加')
const active = ref('')
const getSearch = () => {
  axios.get('https://www.fastmock.site/mock/5903235a886ef1aa2f446afbe614596e/api/search')
}
getSearch()
const handleAdd = () => {
dialogVisible.value=true
isAdding.value=true
title.value='添加'
form.date=''
form.address=''
form.name=''
}
const handleSubmit = () => {
  // tableData.value=[...Object.values(form)]
  if(isAdding.value){
    tableData.value.push(JSON.parse(JSON.stringify(form)))
  }else{
    tableData.value[editingId.value]={...form}
  }
  dialogVisible.value=false
}
const handleEdit = (row:any,index) => {
  dialogVisible.value=true
  isAdding.value=false
  title.value='编辑'
  editingId.value=index
  Object.assign(form,JSON.parse(JSON.stringify(row)))
  console.log(row)
  console.log(index)
}
const handleDelete = (row:any,index) => {
  tableData.value.splice(index,1)
}
</script>
<style scoped>
.add {
  overflow: hidden;
  margin-bottom: 24px;
}
.add button {
  float: right;
}
</style>
